<template>
  <view class="container">
    <!-- 白嫖总计卡片 -->
    <view class="total-card">
      <view class="card-header">
        <text class="title">已白嫖</text>
        <text class="subtitle">本月累计</text>
      </view>
      <view class="amount">
        <text class="currency">¥</text>
        <text class="number">{{ formatMoney(totalAmount) }}</text>
      </view>
      <view class="stats">
        <text class="time">{{ formatTime(totalMinutes) }}</text>
        <text class="count">{{ totalCount }}次</text>
      </view>
    </view>

    <!-- 事件列表 -->
    <view class="events-grid">
      <!-- 添加自定义事件按钮 -->
      <view class="event-item add-event" @tap="showCustomEventModal">
        <text class="icon">➕</text>
        <view class="event-info">
          <text class="name">自定义事件</text>
          <text class="duration">点击添加</text>
        </view>
      </view>
      
      <view 
        v-for="(event, index) in freeEvents"
        :key="index"
        class="event-item"
        :class="event.type"
        @longpress="showEditMenu(event)"
        @tap="startFree(event)"
      >
        <text class="icon">{{ event.icon }}</text>
        <view class="event-info">
          <text class="name">{{ event.name }}</text>
          <text class="duration">{{ event.duration }}分钟</text>
        </view>
        <text class="amount">+¥{{ formatMoney(calculateAmount(event.duration)) }}</text>
      </view>
    </view>

    <!-- 自定义事件弹窗 -->
    <view class="custom-event-modal" v-if="showModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="title">{{ editingEvent ? '编辑事件' : '添加事件' }}</text>
          <text class="close" @tap="closeModal">×</text>
        </view>
        
        <view class="form-item">
          <text class="label">事件名称</text>
          <input 
            type="text" 
            v-model="customEvent.name"
            placeholder="请输入事件名称"
            maxlength="6"
          />
        </view>
        
        <view class="form-item">
          <text class="label">事件图标</text>
          <view class="icon-grid">
            <text 
              v-for="icon in availableIcons" 
              :key="icon"
              :class="['icon-option', { active: customEvent.icon === icon }]"
              @tap="customEvent.icon = icon"
            >{{ icon }}</text>
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">持续时间（分钟）</text>
          <slider
            :value="customEvent.duration"
            :min="1"
            :max="60"
            :step="1"
            show-value
            @change="onDurationChange"
          />
        </view>
        
        <view class="modal-actions">
          <button 
            class="save-btn" 
            @tap="saveCustomEvent"
          >保存</button>
        </view>
      </view>
    </view>

    <!-- 历史记录 -->
    <view class="history-section">
      <view class="section-header">
        <text class="title">白嫖记录</text>
        <view class="actions">
          <text class="reset" @tap="resetEvents">重置</text>
          <text class="clear" @tap="clearHistory">清空</text>
        </view>
      </view>
      <scroll-view 
        class="history-list" 
        scroll-y
        :style="{ height: '400rpx' }"
      >
        <view 
          v-for="(record, index) in freeHistory" 
          :key="index"
          class="history-item"
          :class="record.type"
        >
          <view class="record-info">
            <text class="icon">{{ record.icon }}</text>
            <view class="details">
              <text class="event-name">{{ record.name }}</text>
              <text class="time">{{ formatDateTime(record.timestamp) }}</text>
            </view>
          </view>
          <text class="amount">+¥{{ formatMoney(record.amount) }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

const freeEvents = [
  { 
    name: '上厕所', 
    icon: '🚽', 
    duration: 15, 
    type: 'bathroom'
  },
  { 
    name: '喝水', 
    icon: '🥤', 
    duration: 2, 
    type: 'drink'
  },
  { 
    name: '发呆', 
    icon: '🤔', 
    duration: 1, 
    type: 'daze'
  },
  { 
    name: '伸懒腰', 
    icon: '🧘‍♂️', 
    duration: 3, 
    type: 'stretch'
  },
  { 
    name: '聊天', 
    icon: '💬', 
    duration: 5, 
    type: 'chat'
  },
  { 
    name: '看手机', 
    icon: '📱', 
    duration: 8, 
    type: 'phone'
  },
  { 
    name: '午休', 
    icon: '😴', 
    duration: 30, 
    type: 'nap'
  },
  { 
    name: '摸鱼', 
    icon: '🐟', 
    duration: 10, 
    type: 'slack'
  },
  { 
    name: '吃零食', 
    icon: '🍪', 
    duration: 4, 
    type: 'snack'
  },
  { 
    name: '八卦', 
    icon: '🗣️', 
    duration: 6, 
    type: 'gossip'
  },
  { 
    name: '补妆', 
    icon: '💄', 
    duration: 7, 
    type: 'makeup'
  },
  { 
    name: '网购', 
    icon: '🛒', 
    duration: 12, 
    type: 'shopping'
  }
]

const availableIcons = [
  '😊', '😴', '🎮', '📱', '🎵', '📺', '🎨', '📚',
  '☕️', '🍵', '🥤', '🍪', '🍎', '🍫', '🍕', '🌭',
  '🏃‍♂️', '🚶‍♂️', '🧘‍♂️', '💆‍♂️', '🛀', '🚽', '💅', '💇‍♂️',
  '💬', '🗣️', '📞', '💭', '💤', '🎯', '🎲', '🎸'
]

export default {
  name: 'Free',

  data() {
    return {
      freeEvents: [],
      customEvents: [],
      freeHistory: [],
      totalAmount: 0,
      totalMinutes: 0,
      totalCount: 0,
      showModal: false,
      customEvent: {
        name: '',
        icon: '⌚',
        duration: 5
      },
      availableIcons,
      editingEvent: null
    }
  },

  computed: {
    ...mapState({
      workSettings: state => state.workSettings
    }),

    hourlyRate() {
      const monthlyRate = Number(this.workSettings.salary?.amount) || 0
      return monthlyRate / (22 * 8) // 每月22天，每天8小时
    },

    allEvents() {
      // 移除合并事件的逻辑，直接使用 freeEvents
      return [...this.freeEvents, ...this.customEvents]
    }
  },

  created() {
    this.loadHistory()
    this.loadFreeEvents()
    this.loadCustomEvents()
  },

  methods: {
    formatMoney(amount) {
      if (!amount || isNaN(amount)) return '0.00'
      return Number(amount).toFixed(2)
    },

    formatTime(minutes) {
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`
    },

    formatDateTime(timestamp) {
      const date = new Date(timestamp)
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${month}-${day} ${hours}:${minutes}`
    },

    calculateAmount(minutes) {
      return (this.hourlyRate / 60) * minutes
    },

    startFree(event) {
      // 创建新的事件记录，确保有唯一标识
      const record = {
        ...event,
        timestamp: Date.now(),
        id: `record_${Date.now()}`,
        amount: this.calculateAmount(event.duration)
      }

      // 更新历史记录
      this.freeHistory.unshift(record)
      if (this.freeHistory.length > 50) {
        this.freeHistory.pop()
      }

      // 更新统计数据
      this.totalAmount += record.amount
      this.totalMinutes += event.duration
      this.totalCount++

      // 保存到本地存储
      this.saveHistory()

      // 显示提示
      wx.showToast({
        title: `白嫖到 ¥${this.formatMoney(record.amount)}`,
        icon: 'success',
        duration: 2000
      })
    },

    loadHistory() {
      try {
        const history = wx.getStorageSync('freeHistory')
        const stats = wx.getStorageSync('freeStats')
        if (history) {
          this.freeHistory = history
        }
        if (stats) {
          this.totalAmount = stats.amount || 0
          this.totalMinutes = stats.minutes || 0
          this.totalCount = stats.count || 0
        }
      } catch (error) {
        console.error('Failed to load free history:', error)
      }
    },

    saveHistory() {
      try {
        wx.setStorageSync('freeHistory', this.freeHistory)
        wx.setStorageSync('freeStats', {
          amount: this.totalAmount,
          minutes: this.totalMinutes,
          count: this.totalCount
        })
      } catch (error) {
        console.error('Failed to save free history:', error)
      }
    },

    clearHistory() {
      wx.showModal({
        title: '提示',
        content: '确定要清空所有记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.freeHistory = []
            this.totalAmount = 0
            this.totalMinutes = 0
            this.totalCount = 0
            this.saveHistory()
          }
        }
      })
    },

    showCustomEventModal() {
      this.editingEvent = null
      this.customEvent = {
        name: '',
        icon: '⌚',
        duration: 5
      }
      this.showModal = true
    },

    showEditMenu(event) {
      wx.showActionSheet({
        itemList: ['删除'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.deleteEvent(event)
          }
        }
      })
    },

    editEvent(event) {
      this.editingEvent = event
      this.customEvent = { ...event }
      this.showModal = true
    },

    deleteEvent(event) {
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这个事件吗？',
        success: (res) => {
          if (res.confirm) {
            // 直接从 freeEvents 中删除
            this.freeEvents = this.freeEvents.filter(e => e !== event)
            this.saveFreeEvents()
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },

    closeModal() {
      this.showModal = false
      this.editingEvent = null
    },

    onDurationChange(e) {
      this.customEvent.duration = e.detail.value
    },

    saveCustomEvent() {
      if (!this.customEvent.name.trim()) {
        wx.showToast({
          title: '请输入事件名称',
          icon: 'none'
        })
        return
      }

      if (this.editingEvent) {
        // 编辑现有事件
        const index = this.freeEvents.indexOf(this.editingEvent)
        if (index > -1) {
          this.freeEvents[index] = { ...this.customEvent }
        }
      } else {
        // 添加新事件
        this.freeEvents.push({ ...this.customEvent })
      }

      this.saveFreeEvents()
      this.closeModal()
      
      wx.showToast({
        title: this.editingEvent ? '修改成功' : '添加成功',
        icon: 'success'
      })
    },

    loadCustomEvents() {
      try {
        const customEvents = wx.getStorageSync('customEvents')
        if (customEvents) {
          this.customEvents = customEvents
        }
      } catch (error) {
        console.error('Failed to load custom events:', error)
      }
    },

    saveCustomEvents() {
      try {
        wx.setStorageSync('customEvents', this.customEvents)
      } catch (error) {
        console.error('Failed to save custom events:', error)
      }
    },

    loadFreeEvents() {
      try {
        const savedEvents = wx.getStorageSync('freeEvents')
        if (savedEvents) {
          this.freeEvents = savedEvents
        } else {
          // 首次加载使用默认事件
          this.freeEvents = [
            { name: '上厕所', icon: '🚽', duration: 15, type: 'bathroom' },
            { name: '喝水', icon: '🥤', duration: 2, type: 'drink' },
            { name: '发呆', icon: '🤔', duration: 1, type: 'daze' },
            { name: '伸展', icon: '🧘‍♂️', duration: 3, type: 'stretch' },
            { name: '聊天', icon: '💬', duration: 5, type: 'chat' },
            { name: '玩手机', icon: '📱', duration: 10, type: 'phone' },
            { name: '小憩', icon: '😴', duration: 20, type: 'nap' },
            { name: '摸鱼', icon: '🐟', duration: 30, type: 'slack' },
            { name: '零食', icon: '🍪', duration: 5, type: 'snack' }
          ]
          this.saveFreeEvents()
        }
      } catch (error) {
        console.error('Failed to load free events:', error)
      }
    },

    saveFreeEvents() {
      try {
        wx.setStorageSync('freeEvents', this.freeEvents)
      } catch (error) {
        console.error('Failed to save free events:', error)
      }
    },

    resetEvents() {
      wx.showModal({
        title: '重置事件',
        content: '确定要恢复所有默认事件吗？',
        success: (res) => {
          if (res.confirm) {
            this.loadFreeEvents()
            wx.showToast({
              title: '已恢复默认事件',
              icon: 'success'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f8fafc;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.total-card {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border-radius: 24px;
  padding: 32px;
  color: white;
  box-shadow: 0 8px 24px rgba(59, 130, 246, 0.15);

  .card-header {
    margin-bottom: 24px;

    .title {
      font-size: 40px;
      font-weight: 600;
      display: block;
    }

    .subtitle {
      font-size: 20px;
      opacity: 0.8;
    }
  }

  .amount {
    margin-bottom: 28px;
    display: flex;
    align-items: baseline;

    .currency {
      font-size: 36px;
      margin-right: 4px;
      opacity: 0.9;
    }

    .number {
      font-size: 60px;
      font-weight: 700;
      font-family: 'DIN Alternate', -apple-system, sans-serif;
    }
  }

  .stats {
    display: flex;
    gap: 16px;

    .time, .count {
      background: rgba(255, 255, 255, 0.15);
      padding: 10px 20px;
      border-radius: 20px;
      font-size: 20px;
    }
  }
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 4px;

  .event-item {
    background: white;
    border-radius: 16px;
    padding: 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
    }

    .icon {
      font-size: 48px;
      line-height: 1;
    }

    .event-info {
      text-align: center;

      .name {
        font-size: 22px;
        color: #1e293b;
        font-weight: 500;
        display: block;
      }

      .duration {
        font-size: 18px;
        color: #64748b;
        margin-top: 4px;
      }
    }

    .amount {
      font-size: 20px;
      color: #3b82f6;
      background: #eff6ff;
      padding: 6px 16px;
      border-radius: 12px;
    }
  }
}

.history-section {
  background: white;
  border-radius: 24px;
  padding: 28px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .title {
      font-size: 28px;
      font-weight: 600;
      color: #1e293b;
    }

    .actions {
      display: flex;
      gap: 12px;

      .reset {
        font-size: 20px;
        color: #64748b;
        padding: 8px 20px;
        border-radius: 16px;
        background: #f1f5f9;

        &:active {
          background: #e2e8f0;
        }
      }

      .clear {
        font-size: 20px;
        color: #64748b;
        padding: 8px 20px;
        border-radius: 16px;
        background: #f1f5f9;

        &:active {
          background: #e2e8f0;
        }
      }
    }
  }

  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      border-radius: 16px;
      margin-bottom: 16px;
      background: #f8fafc;

      .record-info {
        display: flex;
        align-items: center;
        gap: 20px;

        .icon {
          font-size: 40px;
          line-height: 1;
        }

        .details {
          .event-name {
            font-size: 24px;
            color: #1e293b;
            display: block;
          }

          .time {
            font-size: 18px;
            color: #64748b;
          }
        }
      }

      .amount {
        font-size: 24px;
        color: #3b82f6;
        font-weight: 500;
      }
    }
  }
}

// 事件类型特殊样式
.event-item {
  &.bathroom { background: linear-gradient(45deg, #ffffff 0%, #f1f5f9 100%); }
  &.drink { background: linear-gradient(45deg, #ffffff 0%, #f0f9ff 100%); }
  &.daze { background: linear-gradient(45deg, #ffffff 0%, #faf5ff 100%); }
  &.stretch { background: linear-gradient(45deg, #ffffff 0%, #f0fdf4 100%); }
  &.chat { background: linear-gradient(45deg, #ffffff 0%, #fff7ed 100%); }
  &.phone { background: linear-gradient(45deg, #ffffff 0%, #fdf2f8 100%); }
  &.nap { background: linear-gradient(45deg, #ffffff 0%, #eff6ff 100%); }
  &.slack { background: linear-gradient(45deg, #ffffff 0%, #f8fafc 100%); }
  &.snack { background: linear-gradient(45deg, #ffffff 0%, #fef2f2 100%); }
  &.gossip { background: linear-gradient(45deg, #ffffff 0%, #fdf4ff 100%); }
  &.makeup { background: linear-gradient(45deg, #ffffff 0%, #fff1f2 100%); }
  &.shopping { background: linear-gradient(45deg, #ffffff 0%, #f0fdfa 100%); }
}

.add-event {
  border: 2px dashed #e2e8f0 !important;
  background: transparent !important;
  
  &:active {
    background: #f8fafc !important;
  }
  
  .icon {
    color: #64748b;
    font-size: 24px;
  }
}

.custom-event-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .modal-content {
    width: 90%;
    max-width: 600rpx;
    background: white;
    border-radius: 24px;
    padding: 24px;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      
      .title {
        font-size: 28px;
        font-weight: 600;
        color: #1e293b;
      }
      
      .close {
        font-size: 24px;
        color: #64748b;
        padding: 4px 12px;
      }
    }
    
    .form-item {
      margin-bottom: 20px;
      
      .label {
        font-size: 20px;
        color: #64748b;
        margin-bottom: 8px;
        display: block;
      }
      
      input {
        width: 100%;
        height: 56px;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 0 16px;
        font-size: 22px;
        color: #1e293b;
      }
      
      .icon-grid {
        display: grid;
        grid-template-columns: repeat(8, 1fr);
        gap: 8px;
        
        .icon-option {
          width: 56px;
          height: 56px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
          border: 1px solid #e2e8f0;
          font-size: 28px;
          transition: all 0.3s ease;
          
          &.active {
            background: #eff6ff;
            border-color: #3b82f6;
          }
          
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
    
    .modal-actions {
      margin-top: 24px;
      
      .save-btn {
        width: 100%;
        height: 56px;
        background: #3b82f6;
        color: white;
        border-radius: 12px;
        font-size: 22px;
        font-weight: 500;
        
        &:active {
          opacity: 0.9;
        }
      }
    }
  }
}
</style> 